//
//  LKImagePickerManager.m
//  LKImagePickerDemo
//
//  Created by LIUKUN-PC on 16/5/26.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "LKImagePickerManager.h"
#import "LKOptionSheetViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImagePickerController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "TZImageManager.h"
#import "MBProgressHUD.h"
#import "UIViewController+LKCurrentViewController.h"

void LKImagePikerGetAssertUrl(PHAsset *asset, void(^completion)(NSURL *url)) {
    
    if (asset.mediaType == PHAssetMediaTypeImage) {\
        
        PHContentEditingInputRequestOptions *options = [[PHContentEditingInputRequestOptions alloc] init];
        [options setCanHandleAdjustmentData:^BOOL(PHAdjustmentData * _Nonnull adjustmentData) {
            return YES;
        }];
        
        [asset requestContentEditingInputWithOptions:options completionHandler:^(PHContentEditingInput * _Nullable contentEditingInput, NSDictionary * _Nonnull info) {
            
            if (completion) {
                completion(contentEditingInput.fullSizeImageURL);
            }
        }];

        
    } else if (asset.mediaType == PHAssetMediaTypeVideo) {
        
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHVideoRequestOptionsVersionOriginal;
        [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            
            if (completion) {
                if ([asset isKindOfClass:[AVURLAsset class]]) {
                    completion(((AVURLAsset *)asset).URL);
                } else {
                    completion(nil);
                }
                
            }
        }];
    }
 
}

@interface LKImagePickerManager () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

//拍照完成后的回调
@property (nonatomic, strong) LKPickImagesFinishedBlock takePhotosDidFinishBlock;

//录制视频完成后的回调
@property (nonatomic, copy) LKPickVideoFinishedBlock videoRecordDidFinishBlock;
//是否为原图
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;
//照片多选拍照控制器
@property (nonatomic, strong) UIImagePickerController *imagePicker;



@end


@implementation LKImagePickerManager

#pragma mark - Init API

+ (instancetype)imagePickerManagerWithCurrentViewController:(UIViewController *)currentViewController {
    LKImagePickerManager *imagePickerManager = [[LKImagePickerManager alloc] init];
    imagePickerManager.currentViewController = currentViewController;
    return imagePickerManager;
}

#pragma mark - Image Picker API

- (void)showImagesPickerSheetViewWithSelectedAssets:(NSMutableArray<PHAsset *> *)selectedAssets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto maxImagesCount:(NSInteger)maxImagesCount didFinishPickingPhotosHandler:(LKPickImagesFinishedBlock)didFinishPickingPhotosBlock {
    LKOptionSheetViewController *optionSheetVC = [[LKOptionSheetViewController alloc] initWithOptionsArray:@[@"拍照", @"从手机相册选择"] didSelectOptionHandler:^(NSInteger index) {
        if (index == 0) {
            [self openCameraWithIsSelectOriginalPhoto:isSelectOriginalPhoto takePhotosDidFinishHandler:didFinishPickingPhotosBlock];
        } else {
            [self pickPhotosWithSelectedAssets:selectedAssets isSelectOriginalPhoto:isSelectOriginalPhoto maxImagesCount:maxImagesCount didFinishPickingPhotosHandler:didFinishPickingPhotosBlock];
        }
    }];
    
    __weak typeof(self) weakSelf = self;
    
    optionSheetVC.cancelBlock = ^ {
        //weakSelf.currentViewController = nil;
    };
    [[self currentViewController] presentViewController:optionSheetVC animated:NO completion:nil];
}

- (void)openCameraWithIsSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto takePhotosDidFinishHandler:(LKPickImagesFinishedBlock)takePhotosDidFinishBlock {
    self.takePhotosDidFinishBlock = takePhotosDidFinishBlock;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePicker.sourceType = sourceType;
        self.imagePicker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [[self currentViewController] presentViewController:self.imagePicker animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开相机,请在真机中使用");
    }

}

- (void)previewPhotosWithSelectedAssets:(NSMutableArray<PHAsset *> *)selectedAssets selectedPhotos:(NSMutableArray<UIImage *> *)selectedPhotos index:(NSInteger)index isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto didChangeSelectedAssetHandler:(LKPickImagesFinishedBlock)didChangeSelectedAssetBlock {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:selectedAssets selectedPhotos:selectedPhotos index:index];
    imagePickerVc.isSelectOriginalPhoto = isSelectOriginalPhoto;
    imagePickerVc.allowPickingVideo = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto) {
        if (didChangeSelectedAssetBlock) {
            didChangeSelectedAssetBlock(photos, assets, isSelectOriginalPhoto, NO);
        }
    }];
    [[self currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
   
}

- (void)pickPhotosWithSelectedAssets:(NSMutableArray<PHAsset *> *)selectedAssets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto maxImagesCount:(NSInteger)maxImagesCount didFinishPickingPhotosHandler:(LKPickImagesFinishedBlock)didFinishPickingPhotosBlock {
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:maxImagesCount delegate:nil];
    imagePickerVC.isSelectOriginalPhoto = isSelectOriginalPhoto;
    imagePickerVC.selectedAssets = selectedAssets;
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto) {
        if (didFinishPickingPhotosBlock) {
            didFinishPickingPhotosBlock(photos, assets, isSelectOriginalPhoto, NO);
        }
    }];
    imagePickerVC.allowPickingVideo = NO;
    [[self currentViewController] presentViewController:imagePickerVC animated:YES completion:nil];
}

#pragma mark - Video Picker API

- (void)showVideoPickerSheetViewWithDidFinishPickingVideoHandler:(LKPickVideoFinishedBlock)didFinishPickingVideoBlock {
    LKOptionSheetViewController *optionSheetVC = [[LKOptionSheetViewController alloc] initWithOptionsArray:@[@"拍摄", @"从手机相册选择"] didSelectOptionHandler:^(NSInteger index) {
        if (index == 0) {
            [self openCameraWithVideoRecordDidFinishHandler:didFinishPickingVideoBlock];
        } else {
            [self pickVideoWithDidFinishPickingVideoHandler:didFinishPickingVideoBlock];
        }
    }];
    
    __weak typeof(self) weakSelf = self;
    
    optionSheetVC.cancelBlock = ^ {
        //weakSelf.currentViewController = nil;
    };
    [[self currentViewController] presentViewController:optionSheetVC animated:NO completion:nil];
}

- (void)openCameraWithVideoRecordDidFinishHandler:(LKPickVideoFinishedBlock)videoRecordDidFinishBlcok {
    self.videoRecordDidFinishBlock = videoRecordDidFinishBlcok;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePicker.sourceType = sourceType;
        self.imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
        self.imagePicker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        //视频最长时间为10分钟
        self.imagePicker.videoMaximumDuration = 600;
        [[self currentViewController] presentViewController:self.imagePicker animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开相机,请在真机中使用");
    }

}

- (void)pickVideoWithDidFinishPickingVideoHandler:(LKPickVideoFinishedBlock)didFinishPickingVideoBlock {
    TZImagePickerController *pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:0 delegate:nil];
    pickerVC.allowPickingImage = NO;
    [pickerVC setDidFinishPickingVideoHandle:^(UIImage *coverImage,id asset) {
        
        __block NSString *path = nil;
        
        //此时self.imagePicker 已经dismiss
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.currentViewController.view animated:YES];
        hud.label.text = @"正在处理";
        
        [[TZImageManager manager] getVideoOutputPathWithAsset:asset completion:^(NSString *outputPath) {
            path = outputPath;
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [hud hideAnimated:YES];
                
                if (didFinishPickingVideoBlock) {
                    didFinishPickingVideoBlock(coverImage, asset, path, NO);
                }
                //[self.imagePicker dismissViewControllerAnimated:YES completion:nil];
            });
            
        }];
        
    }];
    [[self currentViewController] presentViewController:pickerVC animated:YES completion:nil];
    
}



#pragma mark - Getter & Setter

- (UIImagePickerController *)imagePicker {
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

//- (UIViewController *)currentViewController {
//    if (!_currentViewController) {
//        _currentViewController = [UIViewController currentViewController];
//    }
//    return _currentViewController;
//}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    //判断类型，
    PHAssetMediaType assetMediaType = PHAssetMediaTypeUnknown;
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        assetMediaType = PHAssetMediaTypeImage;
    } else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
        assetMediaType = PHAssetMediaTypeVideo;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.imagePicker.view animated:YES];
    hud.label.text = @"正在处理";
    
    __block PHAsset *asset = nil;
    __block UIImage *coverImage = nil;
    __block UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    //iOS8以后有效
    ALAssetsLibrary *assetLabrary = [[ALAssetsLibrary alloc] init];
    
    void(^saveCompletionBlock)(NSURL *assetURL, NSError *error) = ^(NSURL *assetURL, NSError *error) {
        
        PHFetchOptions *option = [[PHFetchOptions alloc] init];
        option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", assetMediaType];
        option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        
        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
        for (PHAssetCollection *collection in smartAlbums) {
            if ([collection.localizedTitle isEqualToString:@"Camera Roll"] || [collection.localizedTitle isEqualToString:@"相机胶卷"] ||  [collection.localizedTitle isEqualToString:@"所有照片"]) {
                PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:option];
                asset = [fetchResult lastObject];
                
            }
        }
        TZImageManager *manager = [TZImageManager manager];
        
        if (assetMediaType == PHAssetMediaTypeImage && self.takePhotosDidFinishBlock) {
            
            //貌似 isSelectOriginalPhoto 没什么用
            /*
            if (!self.isSelectOriginalPhoto) {
                [manager getPhotoWithAsset:asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                    image = photo;
                }];
            }
             */

            [hud hideAnimated:YES];
            
            self.takePhotosDidFinishBlock(@[image], @[asset], self.isSelectOriginalPhoto, YES);
            [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
            
        } else if (assetMediaType == PHAssetMediaTypeVideo && self.videoRecordDidFinishBlock) {
            
            [manager getPhotoWithAsset:asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                coverImage = photo;
            }];
            
            [manager getVideoOutputPathWithAsset:asset completion:^(NSString *outputPath) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //回调或者说是通知主线程刷新，
                    [hud hideAnimated:YES];
                    self.videoRecordDidFinishBlock(coverImage, asset, outputPath, YES);
                    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
                });
  
            }];
        }
    };
    
    if (assetMediaType == PHAssetMediaTypeImage) {
        [assetLabrary writeImageToSavedPhotosAlbum:image.CGImage orientation:(NSInteger)image.imageOrientation completionBlock:saveCompletionBlock];
    } else if (assetMediaType == PHAssetMediaTypeVideo) {
        NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        [assetLabrary writeVideoAtPathToSavedPhotosAlbum:mediaURL completionBlock:saveCompletionBlock];
    }
}

@end
